import axios from 'axios'
import type { AxiosError, AxiosInstance, AxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus'
import storage from '@/utils/storage'

const defaultConfig: AxiosRequestConfig = {
  baseURL: '/api',
  timeout: 1000 * 10
}

class RequestHttp {
  service: AxiosInstance

  constructor(config: AxiosRequestConfig) {
    this.service = axios.create(config)
    /**
     * @description 请求拦截器
     * 客户端发送请求 -> [请求拦截器] -> 服务器
     * token校验(JWT) : 接受服务器返回的 token,存储到 vuex/pinia/本地储存当中
     */
    this.service.interceptors.request.use(
      (config) => {
        const token = storage.get('token')
        if (token) config.headers.Authorization = token
        return config
      },
      (error: AxiosError) => {
        return Promise.reject(error)
      }
    )

    /**
     * @description 响应拦截器
     * 服务器换返回信息 -> [拦截统一处理] -> 客户端JS获取到信息
     */
    this.service.interceptors.response.use(
      (response) => {
        const result = response.data
        if (result.code !== 1000) {
          ElMessage.error(result.message)
          return Promise.reject(result)
        }
        return result.data
      },
      (error: AxiosError) => {
        return Promise.reject(error)
      }
    )
  }

  /**
   * @description 常用请求方法封装
   */
  get<T>(url: string, params?: object, _config = {}): Promise<T> {
    return this.service.get(url, { ..._config, params })
  }

  post<T>(url: string, params?: object, _config: AxiosRequestConfig = {}): Promise<T> {
    return this.service.post(url, params, { ..._config })
  }
}

export default new RequestHttp(defaultConfig)
